﻿using Common.Lib.Dto;
using Common.Lib.Parameter;
using Common.Lib.Service;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.Todo.Extendsions;
using Client.Todo.Common;

namespace Client.Todo.ViewModels
{
    /// <summary>
    /// 待办VM
    /// </summary>
    public class ToDoViewModel : NavigationViewModel
    {

        public ToDoViewModel(IToDoService service,IContainerProvider containerProvider,IDialogHostService dialogHostService):base(containerProvider)
        {
            this.service = service;
            this.containerProvider = containerProvider;
            this.dialogHostService = dialogHostService;
            QueryDataAsync();
        }

        #region 列表

        /// <summary>
        /// 列表
        /// </summary>
        private ObservableCollection<ToDoDto> toDoDtos;

        /// <summary>
        /// 列表
        /// </summary>
		public ObservableCollection<ToDoDto> ToDoDtos
        {
            get { return toDoDtos; }
            set { SetProperty(ref toDoDtos, value); }
        }

        #endregion 列表 

        #region 是否打开右侧

        /// <summary>
        /// 是否打开右侧
        /// </summary>
        private bool _isRightDrawerOpen;

        /// <summary>
        /// 是否打开右侧
        /// </summary>
        public bool IsRightDrawerOpen
        {
            get { return _isRightDrawerOpen; }
            set { SetProperty(ref _isRightDrawerOpen, value); }
        }

        #endregion 是否打开右侧 


        #region 右侧打开

        /// <summary>
        /// 右侧打开 - 命令
        /// </summary>
        private DelegateCommand _rightDrawerOpenCmd;
        private readonly IToDoService service;
        private readonly IContainerProvider containerProvider;
        private readonly IDialogHostService dialogHostService;

        /// <summary>
        /// 右侧打开 - 命令
        /// </summary>
        public DelegateCommand RightDrawerOpenCmd =>
            _rightDrawerOpenCmd ?? (_rightDrawerOpenCmd = new DelegateCommand(ExecuteRightDrawerOpen));

        /// <summary>
        /// 执行 - 右侧打开
        /// </summary>    
        void ExecuteRightDrawerOpen()
        {
            IsRightDrawerOpen = true;
            CurrentDto = new ToDoDto();
        }

        #endregion 右侧打开

        #region 当前选中的值

        /// <summary>
        /// 当前选中的值
        /// </summary>
        private ToDoDto _currentDto;

        /// <summary>
        /// 当前选中的值
        /// </summary>
        public ToDoDto CurrentDto
        {
            get { return _currentDto; }
            set { SetProperty(ref _currentDto, value); }
        }

        #endregion 当前选中的值 

        #region 搜索关键字

        /// <summary>
        /// 搜索关键字
        /// </summary>
        private string _searchKey;

        /// <summary>
        /// 搜索关键字
        /// </summary>
        public string SearchKey
        {
            get { return _searchKey; }
            set { SetProperty(ref _searchKey, value); }
        }

        #endregion 搜索关键字 

        #region 删除

        /// <summary>
        /// 删除 - 命令
        /// </summary>
        private DelegateCommand<ToDoDto> _deleteCmd;

        /// <summary>
        /// 删除 - 命令
        /// </summary>
        public DelegateCommand<ToDoDto> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<ToDoDto>(ExecuteDelete));

        /// <summary>
        /// 执行 - 删除
        /// </summary>    
        async void ExecuteDelete(ToDoDto parameter)
        {
            if(parameter != null)
            {
                var dialogRes = await dialogHostService.Question();
                if(dialogRes.Result != Prism.Services.Dialogs.ButtonResult.OK)
                {
                    return;
                }
                try
                {
                    UpdateLoading(true);
                    var res = await service?.DeleteAsync(parameter.Id.GetValueOrDefault(0));
                    if(res?.Status == true)
                    {
                        ToDoDtos.Remove(parameter);
                    }
                }
                catch
                {

                }
                finally
                {
                    UpdateLoading(false);
                }
            }
        }

        #endregion 删除

        #region 保存

        /// <summary>
        /// 保存 - 命令
        /// </summary>
        private DelegateCommand _saveCmd;

        /// <summary>
        /// 保存 - 命令
        /// </summary>
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSave));

        /// <summary>
        /// 执行 - 保存
        /// </summary>    
        async void ExecuteSave()
        {
            if(string.IsNullOrEmpty(CurrentDto.Title) || string.IsNullOrEmpty(CurrentDto.Content))
            {
                return;
            }
            UpdateLoading(true);
            try
            {
                if (CurrentDto.Id > 0)
                {
                    var updateRes = await service.UpdateAsync(CurrentDto);
                    if (updateRes?.Status == true)
                    {
                        var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                        if (todo != null)
                        {
                            int index = ToDoDtos.IndexOf(todo);
                            ToDoDtos[index] = CurrentDto;
                        }
                    }
                }
                else
                {
                    var addResult = await service.AddAsync(CurrentDto);
                    if (addResult?.Status == true)
                    {
                        ToDoDtos.Insert(0,addResult.Result);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                UpdateLoading(false);
            }
        }

        #endregion 保存

        #region 筛选选中的状态

        /// <summary>
        /// 筛选选中的状态
        /// </summary>
        private int _filterStatusSelectedIndex;

        /// <summary>
        /// 筛选选中的状态
        /// </summary>
        public int FilterStatusSelectedIndex
        {
            get { return _filterStatusSelectedIndex; }
            set 
            { 
                SetProperty(ref _filterStatusSelectedIndex, value); 
                QueryDataAsync();
            }
        }

        #endregion 筛选选中的状态 

        private async void QueryDataAsync()
        {
            UpdateLoading(true);
            var toDoDtos = new List<ToDoDto>();
            //#region 生成测试数据
            //for (int i = 0; i < 20; i++)
            //{

            //    toDoDtos.Add(new ToDoDto()
            //    {
            //        Id = i + 1,
            //        Content = $"待办内容{i + 1}",
            //        Status = i % 2,
            //        CreateTime = DateTime.Now,
            //        Title = $"待办标题{i + 1}",
            //        UpdateTime = DateTime.Now,
            //    });
            //}
            //#endregion 生成测试数据 
            int? status = FilterStatusSelectedIndex == 0 ? null : FilterStatusSelectedIndex - 1;
            var res = await service.GetAllFilterAsync(new ToDoQueryParameter()
            {
                PageIndex = 0,
                PageSize = 100,
                SearchKey = SearchKey,
                Status = status,
            });
            if (res.Status)
            {
                toDoDtos = res.Result.Items.ToList();
                ToDoDtos = new ObservableCollection<ToDoDto>(toDoDtos);
            }
            UpdateLoading(false);
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            QueryDataAsync();
            base.OnNavigatedTo(navigationContext);
        }

        #region 选中

        /// <summary>
        /// 选中 - 命令
        /// </summary>
        private DelegateCommand<ToDoDto> _selectedCmd;

        /// <summary>
        /// 选中 - 命令
        /// </summary>
        public DelegateCommand<ToDoDto> SelectedCmd =>
            _selectedCmd ?? (_selectedCmd = new DelegateCommand<ToDoDto>(ExecuteSelected));

        /// <summary>
        /// 执行 - 选中
        /// </summary>    
        async void ExecuteSelected(ToDoDto parameter)
        {
            if (parameter != null)
            {
                UpdateLoading(true);
                var res = await service.GetFirstOfDefaultAsync(parameter.Id.GetValueOrDefault(0));
                if (res.Status)
                {
                    parameter.Title = res.Result.Title;
                    parameter.Content = res.Result.Content;
                    parameter.Status = res.Result.Status;
                    CurrentDto = parameter;
                    IsRightDrawerOpen = true;
                }
                UpdateLoading(false);
            }
        }

        #endregion 选中

        #region 搜索

        /// <summary>
        /// 搜索 - 命令
        /// </summary>
        private DelegateCommand _searchCmd;

        /// <summary>
        /// 搜索 - 命令
        /// </summary>
        public DelegateCommand SearchCmd =>
            _searchCmd ?? (_searchCmd = new DelegateCommand(ExecuteSearch));

        /// <summary>
        /// 执行 - 搜索
        /// </summary>    
        void ExecuteSearch()
        {
            QueryDataAsync();
        }

        #endregion 搜索
    }
}
